package com.zhongli.devplatform.security.handler;

import com.alibaba.fastjson.JSON;
import com.zhongli.devplatform.po.sys.ReadUserLoginPO;
import com.zhongli.devplatform.service.imp.sys.ReadSystemParameterService;
import com.zhongli.devplatform.service.imp.sys.ReadUserLoginService;
import com.zhongli.devplatform.utils.CusAccessObjectUtil;
import com.zhongli.devplatform.component.SpringUtil;
import com.zhongli.devplatform.bean.Res;
import eu.bitwalker.useragentutils.UserAgent;
import lombok.SneakyThrows;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class MyAuthenticationSuccessHandler implements AuthenticationSuccessHandler {


    @SneakyThrows
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {

        ReadUserLoginService userLoginService = SpringUtil.getBean(ReadUserLoginService.class);

        ReadSystemParameterService systemParameterService = SpringUtil.getBean(ReadSystemParameterService.class);

        String username = httpServletRequest.getParameter("username");

        httpServletResponse.setContentType("application/json;charset=utf-8");

        ReadUserLoginPO readUserLoginPO = new ReadUserLoginPO();
        UserAgent userAgent = UserAgent.parseUserAgentString(httpServletRequest.getHeader("User-Agent"));
        readUserLoginPO.setLoginBrowser(userAgent.getBrowser().getName());
        userAgent.getOperatingSystem().getDeviceType();
        readUserLoginPO.setLoginIp(CusAccessObjectUtil.getIpAddress(httpServletRequest));
        readUserLoginPO.setLoginStatus("1");
        readUserLoginPO.setLoginType("2");
        readUserLoginPO.setLoginUa(httpServletRequest.getHeader("User-Agent"));
        readUserLoginPO.setLoginTime(new Date());
        readUserLoginPO.setUserName(username);
        userLoginService.save(readUserLoginPO);

        PrintWriter out = httpServletResponse.getWriter();
        out.write(JSON.toJSONString(new Res(null)));
        out.flush();
        out.close();


    }
}
